package com.arcvideo.acsplayer.utils;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

import com.arcvideo.acsplayer.mode.InputVideoInfo;

public class DbUtil extends SQLiteOpenHelper {

	private SQLiteDatabase mDb = null;
	public DbUtil(Context context, String name, CursorFactory factory, int version) {
		super(context, name, factory, version);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		mDb = db;
		createTables();
	}

	private void createTables() {
		if (!isTableExists("InputUrlTbl")) {
			mDb.execSQL("create table InputUrlTbl(_id integer primary key autoincrement, playName text, playPath text)");
		}

	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	public boolean isTableExists(String tableName) {
		boolean exist = false;
		Cursor cs = null;
		if (null == tableName || tableName.length() == 0) {
			return false;
		}
		SQLiteDatabase db = null;
		try {
			db = this.getReadableDatabase();
			String sql = "select count(*) as c from sqlite_master where type ='table' and name ='" + tableName.trim() + "'";
			cs = db.rawQuery(sql, null);
			if (cs.moveToNext()) {
				int count = cs.getInt(0);
				if (count > 0) {
					exist = true;
				}
			}
		} catch (Exception e) {

		}
		return exist;
	}

	public ArrayList<InputVideoInfo> getInputVideoInfoList() {
		ArrayList<InputVideoInfo> inputVideoInfoList = new ArrayList<InputVideoInfo>();
		SQLiteDatabase db = getWritableDatabase();
		Cursor cs = db.query("InputUrlTbl", null, null, null, null, null, "_id desc");

		while (cs.moveToNext()) {
			InputVideoInfo info = new InputVideoInfo();
			info.setDisplayName(cs.getString(1));
			info.setPath(cs.getString(2));

			inputVideoInfoList.add(info);
		}
		cs.close();
		db.close();
		return inputVideoInfoList;
	}

	public void addInputVideoInfo(InputVideoInfo inputVideoInfo) {
		if (null == inputVideoInfo)
			return;
		SQLiteDatabase db = getWritableDatabase();
		
		

		ContentValues val = new ContentValues();
		val.put("playName", inputVideoInfo.getDisplayName());
		val.put("playPath", inputVideoInfo.getPath());

		db.insert("InputUrlTbl", null, val);

		db.close();
	}
}
